{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8aff8b21",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-07-13 18:11:25,231 - main - INFO - This is an info message from main logger\n",
      "2025-07-13 18:11:25,235 - main.child - INFO - This is an important info message from child logger\n"
     ]
    }
   ],
   "source": [
    "import logging\n",
    "\n",
    "# 创建一个顶级 Logger\n",
    "logger = logging.getLogger(\"main\")\n",
    "\n",
    "# 配置 Logger 的级别\n",
    "logger.setLevel(logging.DEBUG)\n",
    "\n",
    "# 创建一个 Handler，将日志输出到控制台\n",
    "console_handler = logging.StreamHandler()\n",
    "console_handler.setLevel(logging.INFO)  # Handler 的级别设置为 INFO\n",
    "file_handler = logging.FileHandler(\"main_comprehensive_demo.log\")  # 创建一个 FileHandler，将日志输出到文件\n",
    "file_handler.setLevel(logging.DEBUG)  # Handler 的级别设置为 DEBUG\n",
    "\n",
    "# 创建一个 Formatter，定义日志格式\n",
    "formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n",
    "console_handler.setFormatter(formatter)\n",
    "file_handler.setFormatter(formatter)\n",
    "\n",
    "# 将定义好的各个 Handler 添加到 Logger(只有被正确添加到logger对象的handler才会生效)\n",
    "logger.addHandler(console_handler)\n",
    "logger.addHandler(file_handler)\n",
    "\n",
    "# 创建一个子 Logger (注意父级logger的名字是\"main\",其子级的logger名字以main.<subname>的格式构造)\n",
    "child_logger = logging.getLogger(\"main.child\")\n",
    "child_logger.setLevel(logging.DEBUG)\n",
    "\n",
    "# 配置子 Logger 的过滤器(条件测试函数,返回bool值)\n",
    "def filter_record(record):\n",
    "    # 例如只允许包含 \"important\" 的日志通过,通过判断logger中的msg属性返回布尔值\n",
    "    return \"important\" in record.msg  \n",
    "# 将过滤器添加到logger对象,例如为子级logger配置定义好的过滤器(函数对象)\n",
    "child_logger.addFilter(filter_record)\n",
    "\n",
    "#======== 测试日志记录 ===========\n",
    "logger.debug(\"This is a debug message from main logger\")  # 不会被控制台console_handler记录，因为 console_handler 级别是 INFO;但是因该被file_handler记录,因为file_handler级别是DEBUG\n",
    "logger.info(\"This is an info message from main logger\")   # 会被记录\n",
    "\n",
    "child_logger.debug(\"This is a debug message from child logger\")  # 不会被记录，因为本例的过滤器filter_record要求日志有'important'才被传递,这里的消息中没有,所以被拒绝\n",
    "child_logger.info(\"This is an important info message from child logger\")  # 会被记录,通过过滤器的要求"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6fa2e1ff",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
